package com.qf.controller;

import com.alibaba.druid.util.StringUtils;
import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**登录模块
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/10/12 20:26
 */
@RestController
@RequestMapping("/admin/auth")
//@CrossOrigin("http://localhost")
@Slf4j
public class AdminAuthController {

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    @RequestMapping("/captchaImage")
    public Object captchaImage() throws IOException {
        String code = VerifyCodeUtils.generateVerifyCode(2);

        String uuid = UUID.randomUUID().toString();
//        在缓存区存储验证码
        CaptchaCodeManager.addToCache(uuid,code,5);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        输出图片
        VerifyCodeUtils.outputImage(130,35,outputStream ,code);

        Map<String,Object> data = new HashMap<>();
        data.put("img", Base64.encode(outputStream.toByteArray()));
        data.put("uuid",uuid);

        return ResponseUtil.ok(data);
    }


    @RequestMapping("/login")
    public Object login(@RequestBody Map<String , String> data , HttpSession session){
        log.info("执行登录功能");
        String username = data.get("username");
        String password = data.get("password");
        String code = data.get("code");
        String uuid = data.get("uuid");

        log.debug("登录功能{username: {},password: {}",username, password);

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(code) || StringUtils.isEmpty(uuid)){
            return ResponseUtil.badArgument();
        }

//        校验验证码
        String captcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        if (!code.equalsIgnoreCase(captcha)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }

//        认证
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);

            System.out.println(subject.hasRole("超级管理员"));
        }catch (UnknownAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"未知的账户");
        }catch (CredentialsException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"密码错误");
        }catch (LockedAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"账户已锁定");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"认证错误");
        }

        String id = session.getId();

        return ResponseUtil.ok(id);
    }

    @RequestMapping("/info")
    public Object info(){
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();

        Set<String> roles = roleService.findRoleById(admin.getRoleIds());
        Set<String> perms = permissionService.findById(admin.getRoleIds());

        Map<String,Object> data = new HashMap<>();
        data.put("roles", roles);
        data.put("perms", perms);
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());


        return ResponseUtil.ok(data);

    }

}
